package com.chzc.fm.duotin.ui.mine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chzc.fm.duotin.R;
import com.chzc.fm.duotin.adapter.recyclerview.MineRecyclerAdapter;
import com.chzc.fm.duotin.bean.mine.SpecialBean;
import com.chzc.fm.duotin.bean.mine.UserCenter;
import com.chzc.fm.duotin.db.AlbumDao;
import com.chzc.fm.duotin.db.ContentDao;
import com.chzc.fm.duotin.event.LoginEvent;
import com.chzc.fm.duotin.ui.other.BaseFragment;
import com.chzc.fm.duotin.ui.other.LoginActivity;
import com.chzc.fm.duotin.utils.Blur;
import com.chzc.fm.duotin.utils.ColorUtil;
import com.chzc.fm.duotin.utils.DuotinTask;
import com.chzc.fm.duotin.utils.GlobalParam;
import com.chzc.fm.duotin.utils.HttpUtil;
import com.chzc.fm.duotin.utils.ImageUtil;
import com.chzc.fm.duotin.utils.Unicode2CN;
import com.chzc.fm.duotin.widget.TitleBar;
import com.lzy.widget.PullZoomView;
import com.lzy.widget.manager.ExpandLinearLayoutManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 *
 *  Mine的主界面
 * Created by BillSinla on 2016/6/23.
 */
public class MineFragment extends BaseFragment implements View.OnClickListener{

    private TitleBar titleBar;
    private RecyclerView recyclerView;
    //bean
    private UserCenter user;
    //主布局
    private PullZoomView pzv;
    //主布局的四个参数  敏感度，动画返回的时间， 返回的层叠效果， 是否变大图片
    private float sensitive = 1.3f;
    private int zoomTime = 900;
    private boolean isParallax = false;
    private boolean isZoomEnable = true;

    private TextView textDownload;

    //订阅，关注，赞，历史
    private TextView textSubscribe, textFollow, textLike, textHistory;

    //四个的容器，用来相应事件
    private LinearLayout llSubscribe, llFollow, llLike, llHistory;

    //下载管理和登录按钮
    private TextView textLoad, textLogin, textName;

    //头像图片
    private ImageView imageAvatar, imageBg;

    //没有下载的信息
    private LinearLayout llNoneLoad;

    //专辑的数据库信息
    private List<SpecialBean> specialBeanList;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initViews() {
        EventBus.getDefault().register(this);

        titleBar = (TitleBar) root.findViewById(R.id.title_bar);

        recyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);
        pzv = (PullZoomView) root.findViewById(R.id.pzv);

        textSubscribe = (TextView) root.findViewById(R.id.tv_mine_subscribe);
        textFollow = (TextView) root.findViewById(R.id.tv_mine_follow);
        textLike = (TextView) root.findViewById(R.id.tv_mine_like);
        textHistory = (TextView) root.findViewById(R.id.tv_mine_history);

        llSubscribe = (LinearLayout) root.findViewById(R.id.ll_mine_subscribe);
        llFollow = (LinearLayout) root.findViewById(R.id.ll_mine_follow);
        llLike = (LinearLayout) root.findViewById(R.id.ll_mine_like);
        llHistory = (LinearLayout) root.findViewById(R.id.ll_mine_history);

        imageBg = (ImageView) root.findViewById(R.id.iv_mine_bg);
        imageAvatar = (ImageView) root.findViewById(R.id.iv_mine_avatar);
        textName = (TextView) root.findViewById(R.id.tv_mine_nick_name);
        textLogin = (TextView) root.findViewById(R.id.tv_mine_login);

        textLoad = (TextView) root.findViewById(R.id.tv_mine_load); //下载管理图标
        textDownload = (TextView) root.findViewById(R.id.tv_mine_download); //进入下载界面

        llNoneLoad = (LinearLayout) root.findViewById(R.id.ll_mine_unload);
    }

    @Override
    protected void initEvent() {
        llSubscribe.setOnClickListener(this);
        llFollow.setOnClickListener(this);
        llLike.setOnClickListener(this);
        llHistory.setOnClickListener(this);

        textLoad.setOnClickListener(this);

        imageAvatar.setOnClickListener(this);
        textLogin.setOnClickListener(this);

        textDownload.setOnClickListener(this);

        titleBar.setLeftListener(new TitleBar.mTitleBarListener() {
            @Override
            public void onClick(View v) {
                if(GlobalParam.USER_KEY == "") {
                    startLoginActivity();
                }else {
                    Intent i = new Intent(getActivity(), MsgCenterActivity.class);
                    startActivity(i);
                }
            }
        });
    }

    @Override
    protected void initData() {
        titleBar.setLeft(true, R.drawable.ic_action_bar_message);
        textLoad.setVisibility(View.INVISIBLE);
        textName.setVisibility(View.INVISIBLE);
        if(GlobalParam.USER_KEY != "") {
            UpdateInfo();
        }

        getDataBaseDate();


        pzv.setIsParallax(isParallax);
        pzv.setIsZoomEnable(isZoomEnable);
        pzv.setSensitive(sensitive);
        pzv.setZoomTime(zoomTime);


    }

    /**
     * 更新数据库数据
     */
    public void getDataBaseDate(){
        AlbumDao albumDao = new AlbumDao(getActivity());
        ContentDao contentDao = new ContentDao(getActivity());

        specialBeanList = new ArrayList<SpecialBean>();
        List<SpecialBean.AlbumBean> albumList = albumDao.getAlbums();

        if(albumList.size() > 0){
            for (SpecialBean.AlbumBean album:albumList) {
                SpecialBean special = new SpecialBean();
                special.setAlbum(album);
                special.setContent_list(contentDao.getContent(album.getId()));
                specialBeanList.add(special);
            }
            llNoneLoad.setVisibility(View.GONE);
            recyclerView.setLayoutManager(new ExpandLinearLayoutManager(getActivity()));

            MineRecyclerAdapter adapter = new MineRecyclerAdapter(getActivity(), specialBeanList);
            recyclerView.setAdapter(adapter);
            textLoad.setVisibility(View.VISIBLE);
        }else{
            recyclerView.setVisibility(View.VISIBLE);
            textLoad.setVisibility(View.GONE);
        }



    }

    /**
     * 获取更新数据之后的数据赋值
     */
    private void init() {
        UserCenter.MessageBean msg = user.getMessage();
        textSubscribe.setText("" + msg.getSubscribe().getNum());
        textFollow.setText("" + msg.getFollow().getNum());
        textLike.setText("" + msg.getLike().getNum());

        final UserCenter.UserBean userBean = user.getUser();

        ImageLoader.getInstance().displayImage(userBean.getImage_url(), imageAvatar, ImageUtil.getCircleOptions());
        textName.setVisibility(View.VISIBLE);
        textName.setText(userBean.getReal_name());
        textLogin.setVisibility(View.GONE);

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = ImageLoader.getInstance().loadImageSync(userBean.getImage_url());
                final Bitmap blurMap = Blur.fastblur(getActivity(), bitmap, 20);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageBg.setImageBitmap(blurMap);
                    }
                });
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_mine_subscribe:
                if(GlobalParam.USER_KEY == "") {
                    startLoginActivity();
                }else {
                    Intent i = new Intent(getActivity(), SubscribeActivity.class);
                    startActivity(i);
                }
                break;
            case R.id.ll_mine_follow:
                if(GlobalParam.USER_KEY == "") {
                    startLoginActivity();
                }else {
                    Intent i = new Intent(getActivity(), FollowActivity.class);
                    startActivity(i);
                }
                break;
            case R.id.ll_mine_like:
                if(GlobalParam.USER_KEY == "") {
                    startLoginActivity();
                }else {
                    Intent i = new Intent(getActivity(), LikeActivity.class);
                    startActivity(i);
                }
                break;
            case R.id.ll_mine_history:
                break;
            case R.id.iv_mine_avatar:
                if(GlobalParam.USER_KEY == "") {
                    startLoginActivity();
                }else{
                    startEditInfoActivity();
                }
                break;
            case R.id.tv_mine_login:
                if(GlobalParam.USER_KEY == "") {
                    startLoginActivity();
                }else{
                    startEditInfoActivity();
                }
                break;
            case R.id.tv_mine_load:
                startLoadActivity();
                break;

            case R.id.tv_mine_download:
                Intent intent = new Intent(getActivity(), DownloadActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 更新个人信息
     */
    private void UpdateInfo(){
        DuotinTask.IRequest request = new DuotinTask.IRequest() {
            @Override
            public Object doRequest() {
                return Unicode2CN.unicode2GBK(HttpUtil.doGet(GlobalParam.MINE_URL).toString());
            }
        };

        DuotinTask.IRequestCallback callback = new DuotinTask.IRequestCallback() {
            @Override
            public void success(Object object) {
                try {
                    JSONObject root = new JSONObject(object.toString());
                    String msg = root.getString(GlobalParam.ERROR_MSG);
                    if (GlobalParam.SUCCESS.equals(msg)) {
                        JSONObject data = root.getJSONObject(GlobalParam.DATA);
                        user = UserCenter.objectFromData(data.toString());
                        init();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(String msg) {

            }
        };

        DuotinTask task = new DuotinTask(request, callback);
        putAsyncTask(task);
    }

    /**
     * 开启个人信息的界面
     */
    private void startEditInfoActivity() {
        Intent i = new Intent(getActivity(), EditInfoActivity.class);
        startActivity(i);
    }

    /**
     * 打开下载管理界面
     */
    private void startLoadActivity() {
        Intent i = new Intent(getActivity(), DownloadMangerActivity.class);
        startActivity(i);
    }

    /**
     * 打开登陆界面
     */
    private void startLoginActivity() {
        Intent i = new Intent(getActivity(), LoginActivity.class);
        startActivity(i);
        getActivity().overridePendingTransition(R.anim.activity_open, 0);
    }

    /**
     * eventBus处理登录回调的函数
     * @param event
     */
    @Subscribe
    public void onEventMainThread(LoginEvent event){
        UpdateInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
